#include <stdio.h>
#include <windows.h>
#include <tlhelp32.h>
#include <process.h>

/*
	Usage : judgekill ProcessName
*/
int main( int argc, char *argv[] )
{
	int intNum = 0;
	BOOL bOK = TRUE;
	PROCESSENTRY32 infoProcess;
	HANDLE hSnapshot = INVALID_HANDLE_VALUE;
	char *szProcessName = NULL;

	::SetErrorMode( SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS );

	if( argc < 2 )
	{
		printf( "invalid process name" );
		return 2;
	}
	szProcessName = argv[1];
	
	hSnapshot = ::CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS , GetCurrentProcessId() );
	if( hSnapshot == INVALID_HANDLE_VALUE )
	{
		printf( "error create snapshot,last error(%d).\n", GetLastError() );
		return 1;
	}
	intNum = 0;
	bOK = ::Process32First( hSnapshot, &infoProcess );
	while( bOK )
	{
		if( strstr( infoProcess.szExeFile, szProcessName ) )
		{
			HANDLE hProcess = ::OpenProcess( PROCESS_ALL_ACCESS, FALSE, infoProcess.th32ProcessID );
			if( hProcess == INVALID_HANDLE_VALUE )
			{
				printf( "error open process(id:%d),last error(%d).\n", 
					infoProcess.th32ProcessID, 
					GetLastError() );
				::CloseHandle( hSnapshot );
				return 1;
			}
			TerminateProcess( hProcess , 0 );
			printf( "Killed process(name:%s,id:%u).\n", infoProcess.szExeFile, infoProcess.th32ProcessID );
			intNum ++;
		}
		bOK = ::Process32Next( hSnapshot, &infoProcess );
	}

	CloseHandle( hSnapshot );
	printf( "Killed:%d\n", intNum );

	return 0;
}